package com.apcc4m.sfpush.handler;

import java.net.URI;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;

import com.apcc4m.sfpush.SfpushConst;
import com.apcc4m.sfpush.listener.NettyServerListener;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;

public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private NettyServerListener serverListener;
    private String deviceId;
    private boolean isMng = false;

    public HttpRequestHandler(NettyServerListener serverListener) {
        super();
        this.serverListener = serverListener;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        if (!isMng) {
            serverListener.removeUserChannel(deviceId);
        }
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        if (checkUrl(msg.uri())) {
            if (!isMng) {
                serverListener.saveUserChannel(deviceId, ctx);
                ctx.channel().attr(SfpushConst.KEY_DEVICE_ID).set(deviceId);
            }
            // 从pipeline上由前向后的调用handler
            ctx.fireChannelRead(msg.retain());
        } else {
            ctx.close();
        }
    }

    public boolean checkUrl(String strUrl) {
        boolean result = false;

        try {
            URI uri = new URI(strUrl);
            if ("/connect".equals(uri.getPath()) && uri.getQuery() != null) {
                result = checkUser(uri.getQuery());
                isMng = false;
            } else if ("/mng".equals(uri.getPath()) && uri.getQuery() != null) {
                result = checkMng(uri.getQuery());
                isMng = true;
            }
        } catch (Exception e) {
        }
        return result;
    }

    public boolean checkUser(String query) {
        boolean result = false;
        String token = "";
        String deviceId = "";
        List<NameValuePair> list = URLEncodedUtils.parse(query, Charset.forName("UTF-8"));
        for (NameValuePair item : list) {
            if ("token".equals(item.getName())) {
                token = item.getValue();
            }
            if ("deviceId".equals(item.getName())) {
                deviceId = item.getValue();
            }
        }
        if (SfpushConst.USER_TOKEN.equals(token) && StringUtils.isNotEmpty(deviceId)) {
            result = true;
            this.deviceId = deviceId;
        }
        return result;
    }

    public boolean checkMng(String query) {
        boolean result = false;
        String token = "";
        String deviceId = "";
        List<NameValuePair> list = URLEncodedUtils.parse(query, Charset.forName("UTF-8"));
        for (NameValuePair item : list) {
            if ("token".equals(item.getName())) {
                token = item.getValue();
            }
            if ("deviceId".equals(item.getName())) {
                deviceId = item.getValue();
            }
        }
        if (SfpushConst.MNG_TOKEN.equals(token)) {
            result = true;
            this.deviceId = deviceId;
        }
        return result;
    }
}
